package com.marry.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.marry.entity.Album;
import com.marry.model.Result;
import com.marry.repository.AlbumRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口
 */
@RestController
@RequestMapping("/sys/album")
public class AlbumController {

    @Value("${file.path}")
    private String filePath;
    @Value("${project.url}")
    private String projectUrl;

    @Autowired
    private AlbumRepository albumRepository;

    /**
     * 文件上传
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) {
        String index = request.getParameter("index");
        try {
            if(file!=null){
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                String uuid = IdUtil.simpleUUID();
                fileName = uuid + suffix;
                File imageFile = new File(filePath,fileName);
                FileUtil.writeFromStream(file.getInputStream(), imageFile);
                String imagesUrl = projectUrl + "/file/" + fileName;
                Map<String, Object> map = new HashMap<>();
                map.put("index",index);
                map.put("image",imagesUrl);
                return Result.ok(map);
            }else{
                return Result.error();
            }
        } catch (Exception e) {
            return Result.error();
        }
    }

    /**
     * 获取
     */
    @PostMapping("/save")
    public Result save(@RequestBody List<Album> list) {
        albumRepository.deleteAll();
        list.forEach(entity->{
            if(StringUtils.isNotBlank(entity.getImage())){
                albumRepository.saveAndFlush(entity);
            }
        });
        return Result.ok(list);
    }

    /**
     * 获取
     */
    @PostMapping("/list")
    public Result list() {
        List<Album> list = albumRepository.findAll();
        return Result.ok(list);
    }
}
